package com.tsfyun.scm.controller.finance;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import com.github.pagehelper.PageInfo;
import com.tsfyun.common.base.annotation.DuplicateSubmit;
import com.tsfyun.common.base.dto.Result;
import com.tsfyun.common.base.util.LocalDateTimeUtils;
import com.tsfyun.common.base.util.StringUtils;
import com.tsfyun.scm.dto.finance.ImpSalesContractQTO;
import com.tsfyun.scm.service.finance.IImpSalesContractService;
import com.tsfyun.scm.vo.finance.ImpSalesContractDetailPlusVO;
import com.tsfyun.scm.vo.finance.ImpSalesContractPlusVO;
import com.tsfyun.scm.vo.finance.ImpSalesContractVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;

import com.tsfyun.common.base.controller.BaseController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 销售合同 前端控制器
 * </p>
 *
 * @since 2020-05-19
 */
@Slf4j
@RestController
@RequestMapping("/impSalesContract")
public class ImpSalesContractController extends BaseController {

    @Autowired
    private IImpSalesContractService impSalesContractService;

    @Value("${file.directory}")
    private String filePath;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    /**
     * 分页查询（带客户权限判断）
     * @param qto
     * @return
     */
    @PostMapping(value = "list")
    public Result<List<ImpSalesContractVO>> pageList(@ModelAttribute ImpSalesContractQTO qto) {
        PageInfo<ImpSalesContractVO> page = impSalesContractService.pageList(qto);
        return success((int)page.getTotal(),page.getList());
    }

    /**
     * 明细
     * @param id
     * @param operation
     * @return
     */
    @PostMapping(value = "detail")
    public Result<ImpSalesContractDetailPlusVO> detail(@RequestParam(value = "id") Long id, @RequestParam(value = "operation",required = false)String operation) {
        return success(impSalesContractService.detail(id,operation));
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DuplicateSubmit
    @PostMapping(value = "delete")
    public Result<Void> delete(@RequestParam(value = "id") Long id) {
        impSalesContractService.delete(id);
        return success();
    }

    /**=
     * 获取合同数据
     * @param id
     * @return
     */
    @PostMapping(value = "contractData")
    public Result<ImpSalesContractPlusVO> contractData(@RequestParam(value = "id")Long id){
        return success(impSalesContractService.getContractData(id));
    }

    @GetMapping(value = "exportPdf")
    public Result<Long> exportPdf(@RequestParam(value = "id")Long id){
        return Result.success(impSalesContractService.contractPdf(id));
    }

    /**
     * 导出
     * @param ids
     * @param request
     * @param response
     */
    @GetMapping(value = "/batchDownloadZip")
    public void batchDownloadZip(@RequestParam(value = "ids")String ids, HttpServletRequest request, HttpServletResponse response){
        OutputStream outputStream = null;
        List<File> files = null;
        File zipFile = null;
        try{
            files = impSalesContractService.batchDownloadZip(StringUtils.stringToLongs(ids));
            String zipFileName = LocalDateTimeUtils.formatNow("yyyyMMddHHmmssSSS") + ".zip";
            zipFile = FileUtil.file(filePath +"temp/"+ "scm" +"/salesContract/" + zipFileName);
            ZipUtil.zip(FileUtil.file(filePath +"temp/"+ "scm" +"/salesContract/" + zipFileName),false,files.toArray(new File[files.size()]));
            response.setContentType("application/x-download");
            response.setHeader("Content-disposition","attachment;filename=" + URLEncoder.encode(StrUtil.format("批量下载合同{}",LocalDateTimeUtils.formatNow("yyyyMMddHHmmssSSS")), "UTF-8") + ".zip");
            outputStream = response.getOutputStream();
            FileUtil.writeToStream(zipFile,outputStream);
            outputStream.flush();
        } catch (Exception e){
            log.error("导出文件异常",e);
        } finally {
            if(Objects.nonNull(outputStream)) {
                IOUtils.closeQuietly(outputStream);
            }
            //启动子线程删除文件
            List<File> finalFiles = files;
            File finalZipFile = zipFile;
            threadPoolTaskExecutor.execute(() -> {
                if(CollUtil.isNotEmpty(finalFiles)) {
                    finalFiles.stream().forEach(File::delete);
                }
                if(Objects.nonNull(finalZipFile) && finalZipFile.exists()) {
                    finalZipFile.delete();
                }
            });

        }
    }

}

